package com.bianguo.android.httplibrary;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.fastjson.JSON;
import com.bianguo.android.httplibrary.listener.CallBackListener;
import com.bianguo.android.httplibrary.listener.IJsonDataListener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JsonCallBackListener<T> implements CallBackListener {

    private Class<T> responseClass;
    private IJsonDataListener jsonDataListener;
    private Handler mHandler;

    public JsonCallBackListener(Class<T> responseClass, IJsonDataListener jsonDataListener) {
        this.responseClass = responseClass;
        this.jsonDataListener = jsonDataListener;
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public void success(InputStream inputStream) {
        String response = getContent(inputStream);
        final T clazz = JSON.parseObject(response, responseClass);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                jsonDataListener.success(clazz);
            }
        });
    }

    @Override
    public void failure(String msg) {
        jsonDataListener.failed(msg);
    }

    private String getContent(InputStream inputStream) {
        String content = null;
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content;
    }
}
